const { join, resolve } = require('path');
const webpack = require('webpack');
const {AppendPlugin,OverPlugin} = require('./append.plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const devToolPlugin = require('./util').devToolPlugin;
const CopyWebpackPlugin = require("copy-webpack-plugin");

//无更新不打包
const fs = require('fs');
let gitVersion=null,needBuild=true,d=null;
const githubPath = join(__dirname,'../../github.js');
const dist = {
	entry:{
		test:githubPath
	},
	mode:"none",
	output:{
		path:join(__dirname,'../../'),
		filename:'test.js'
	}
}

if(fs.existsSync(githubPath)){
	//如果存在,则需要判断git版本号是否有变更
	gitVersion = require(githubPath);
	d = fs.readFileSync(join(__dirname,'../.git/HEAD'),{encoding:"utf-8"});
	if(/^ref:/.test(d)){
		d = fs.readFileSync(join(__dirname,'../.git',d.replace(/^ref:\s*|\s*$/g,'')),{encoding:"utf-8"});
	}
	if(gitVersion[__dirname]==d){
		needBuild=false;
	}
}


module.exports = function (moduleId,isNotDev) {
	// moduleId='simulator',isNotDev=true;
	if(isNotDev&&!needBuild){
		return dist;
	}
	const resp = {
		entry: {
			[moduleId]:join(__dirname, `../src/modules/${moduleId}/index.ts`)
		},//已多次提及的唯一入口文件
		output: {
			publicPath: "../../modules/",
			path: join(__dirname, "../dist/modules"),//打包后的文件存放的地方
			filename:`${moduleId}/index.js`,
			chunkFilename:`${moduleId}/[name].[contenthash].js`,//打包后输出文件的文件名
			libraryTarget: "umd",
			library:`webpack_modules_${moduleId}`,
			jsonpFunction:`webpackJsonp_${moduleId}`
		},
		resolve: {
			modules:[join(__dirname,'../src/common/less'),join(__dirname,'../node_modules')],
			extensions: ['.js', '.vue', '.json', '.ts'],
			alias: {
				'vue$': 'vue/dist/vue.esm.js',
				'@': resolve('src'),
				"tsservice":resolve("src/service"),
				"tscomponents":resolve("src/components"),
				"tsmodules":resolve("src/modules"),
				"tscommon":resolve("src/common"),
				"tsdomain":resolve("src/store")
			}
		},
		externals: {
			vue: "Vue",
			vuex: "Vuex",
			"vue-router": "VueRouter",
			"axios": "axios",
			"element-ui":"ELEMENT",
			'vant':'vant',
			'socket.io-client':'io',
			'tsmodules/module': 'loadModules',
			'system.global': 'global zxlib.zxglobal',
			'tscommon/ts/tools/base': 'global zxlib.zxtools.baseConstant',
			'tscommon/ts/tools/base/index': 'global zxlib.zxtools.baseConstant',
			'tscommon/ts/vue/Vue.ext':'global zxlib.zxvue.VueExt',
			'tscommon/ts/vue/dom.ext':'global zxlib.zxvue.DomExt',
			'tscommon/ts/vue/vm.ext':'global zxlib.zxvue.VmExt',
			'tscommon/ts/tools/Encrypt':'global zxlib.zxtools.Encrypt',
			'tscommon/ts/tools/Events':'global zxlib.zxtools.Events',
			'tscommon/ts/tools/ext':'global zxlib.zxtools.ToolsExt',
			'tscommon/ts/tools/Socket.io':'global zxlib.zxtools.SocketIO',
			'tscommon/ts/tools/TreeUtil':'global zxlib.zxtools.TreeUtil',
			'tscommon/ts/tools/Valid.tools':'global zxlib.zxtools.ValidTools',
			'tscommon/ts/base': 'global zxlib.zxtools.baseConstant',
			'tscommon/ts/base/index': 'global zxlib.zxtools.baseConstant',
			'tsservice/commonService': 'global zxlib.zxdomain.commonService',
			'tscommon/ts/tools/domain': 'global zxlib.zxtools.DomainTools',
			'tsdomain/Dict': 'global zxlib.zxdomain.dictService',
			'tsdomain/Default': 'global zxlib.zxdomain.defaultService'
		},
		mode:isNotDev?"production":"development",
		module: {
			rules: [
				{
					test: /(\.ts)$/,
					use: [{
						loader: "babel-loader",
						options: {
							presets: [
								"es2015", "stage-2"
							],
							"plugins": ["transform-es2015-modules-umd"]
						}
					},
					{
						loader: 'ts-loader',
						options: {
							appendTsSuffixTo: [/\.vue$/]
						}
					}],
					exclude: /node_modules/
				},
				{
					test: /\.(less|css)/,
					use: [
						{
								loader: "style-loader"
						}, {
								loader: "css-loader",
								options: {
										modules: false
								}
						}, {
								loader: "postcss-loader"
						}, {
								loader: "less-loader"
						}
					]
				},
				{
					test: /\.vue$/,
					loader: 'vue-loader'
				},{
					test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
					loader: "url-loader?limit=8192&name=assets/[name].[hash].[ext]"
				},{
					test: /\.(png|jpe?g|gif)$/i,
					loaders: [
					'url-loader?limit=8192&name=img/[name].[hash].[ext]',
					'image-webpack-loader?{progressive:true, optimizationLevel: 7, interlaced: false, pngquant:{quality: "65-90", speed: 4}}'
					]
				}
			]
		},
		plugins: [
			new VueLoaderPlugin(),
			new AppendPlugin(moduleId,`__loadOver&&__loadOver(webpack_modules_${moduleId});`),
			new webpack.BannerPlugin('zengxiao版权所有，翻版必究:'+new Date())
		]
	}
	if(isNotDev){
		resp.plugins.unshift(new CleanWebpackPlugin([`modules/${moduleId}`],{
			root:resolve(__dirname,'../dist'),
			verbose:true
		}));
		if(fs.existsSync(join(__dirname, `../static/modules/${moduleId}`))){
			resp.plugins.push(new CopyWebpackPlugin([{
				from: join(__dirname, `../static/modules/${moduleId}`),
				to: join(__dirname, `../dist/modules/${moduleId}`)
			}]));
		}
		resp.plugins.push(devToolPlugin("modules",`./${moduleId}/sourcemap`));
		resp.plugins.push(new OverPlugin(()=>{
			if(gitVersion==null)return;
			gitVersion[__dirname]=d;
			fs.writeFileSync(githubPath,`module.exports=${JSON.stringify(gitVersion)}`,{encoding:"utf-8"});
		},moduleId));
	}
	return resp;
}